import { useState, useEffect, Fragment } from 'react'
import { Form, Button } from 'antd-mobile'
import { Input } from '@/components/FormItems'
import './index.less'

/**
 * 表单项类型
 * @type { 'input' | 'number' | 'picker' | 'searchSelect' | 'switch' | string }
 */
type FormItemTypeType = 'input' | 'number' | 'picker' | 'searchSelect' | 'switch'

/**
 * 表单项
 * @type { type: FormItemTypeType, formProps: { name: string, label: string, visibleField?: string, visibleRule?: (formData: any, visibleField: string) => boolean, }, itemProps: { dictionary?: string, isSystemDictionary?: boolean, initialValue?: any, disabled?: boolean } }
 */
type FormItemType = {
  type: FormItemTypeType,
  formProps: {
    name: string,
    label: string,
    visibleField?: string,
    visibleRule?: (formData: any, visibleField: string) => boolean,
  },
  itemProps: {
    dictionary?: string,
    isSystemDictionary?: boolean,
    initialValue?: any
    disabled?: boolean
  }
}

/**
 * 多表单-表单项
 */
type MultipleFormItemType = {
  header: React.ReactNode,
  formList: FormItemType[]
}

type PropsType = {
  formList: FormItemType[] | MultipleFormItemType[],
  multipleFormList?: boolean,
  customFooter?: React.ReactNode,
}

const FormItem = Form.Item
const Header = Form.Header

const FormList = (props: PropsType) => {

  const {
    formList = [],
    multipleFormList = false,
    customFooter = null
  } = props

  const renderMultipleFormItem = (item: MultipleFormItemType, index: number) => {
    const { header, formList: multipleFormList } = item
    return <Fragment key={index}>
      <Header>{header}</Header>
      {
        multipleFormList.map((item: FormItemType, index: number) => {
          return renderFormItem(item, index)
        })
      }
    </Fragment>
  }

  const renderFormItem = (item: FormItemType, index: number) => {
    const { formProps, itemProps } = item
    const { name, label } = formProps
    switch (item.type) {
      case 'input':
        return <FormItem name={name} label={label} key={index}>
          <Input {...itemProps} />
        </FormItem>
      default:
        return <Input />
    }
  }

  const renderFormItems = () => {
    if (!multipleFormList) {
      return (formList as FormItemType[]).map((item, index) => {
        return renderFormItem(item, index)
      })
    } else {
      return (formList as MultipleFormItemType[]).map((item, index) => {
        return renderMultipleFormItem(item, index)
      })
    }
  }

  return <div className={'form-list'}>
    <Form
      layout='horizontal'
      footer={customFooter || <>
        <Button block type='submit' color='primary' size='large'>
          提交
        </Button>
      </>}
    >
      {renderFormItems()}
    </Form>
  </div>
}

export default FormList
export type {
  FormItemTypeType,
  FormItemType
}
